import fs from "fs";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
import { exists } from "./file";

const __dirname = dirname(fileURLToPath(import.meta.url));

export const log = async (
  file: string,
  level: string,
  content: string | Buffer<ArrayBufferLike>,
  append = false
) => {
  const logsDir = join(__dirname, `../../logs`)
  if (!(await exists(logsDir))) {
    await fs?.promises?.mkdir(logsDir);
  }
  const dirname = file?.replace(/\.(xlsx|xlsm|pdf|words|png|jpeg|jpg)$/g, "");
  const dirpath = join(logsDir, dirname);
  if (!(await exists(dirpath))) {
    await fs?.promises?.mkdir(dirpath);
  }
  if (append) {
    await fs.promises.appendFile(join(dirpath, level), content);
    return;
  }
  await fs.promises.writeFile(join(dirpath, level), content);
};
